package ThreadPoolnio1;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIOClient {
    private SocketChannel socketChannel = null;
    private String ip = null;
    private int port;
    ByteBuffer buff = ByteBuffer.allocate(1024);

    public NIOClient(String ip , int port){
        try{
            this.ip = ip;
            this.port = port;
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress(ip,port));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public  void sendMsg(String msg){
        try {
            if(socketChannel !=null && socketChannel.finishConnect()){
                int i = 0;
            if (msg != null && msg.length() > 0){
                buff.clear();
                buff.put(msg.getBytes("GBK"));
                buff.flip();
                while (buff.hasRemaining()){
                    socketChannel.write(buff);
                    socketChannel.write(ByteBuffer.wrap("\r\n".getBytes()));
                }
            }
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void sendFile(String file){
        try{
            if(socketChannel != null && socketChannel.finishConnect()){
                if(file != null && file.length() > 0){
                    FileInputStream fin = new FileInputStream(file);
                    FileChannel fileChannel = fin.getChannel();
                    int count = -1;
                    while ((count = fileChannel.read(buff)) != -1){
                        buff.flip();
                        socketChannel.write(buff);
                        //加上一个换行符
                        socketChannel.write(ByteBuffer.wrap("\r\n".getBytes()));
                        buff.clear();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public  void closed(){
        try {
            if(socketChannel != null)
                socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  
}
